package com.example.venadaoa.tool;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Display;
import android.view.WindowManager;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Formatter;
import java.util.List;
import java.util.Locale;

/**
 * 工具类
 */
public class Utils {

    /**
     * classname是否运行
     *
     * @param mContext
     * @param activityClassName
     * @return
     */
    public static boolean isActivityRunning(Context mContext, String activityClassName) {
        android.app.ActivityManager activityManager = (android.app.ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> info = activityManager.getRunningTasks(1);
        if (info != null && info.size() > 0) {
            ComponentName component = info.get(0).topActivity;
            if (activityClassName.equals(component.getClassName())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取系统版本号
     */
    public static String getDeviceOSVersion() {
        // 系统版本号
        String deviceOSVersion = android.os.Build.VERSION.RELEASE;
        return deviceOSVersion;
    }

    /**
     * 获取电话号码
     */
    public static String getNativePhoneNumber(Context context) {
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        String NativePhoneNumber = telephonyManager.getLine1Number();
        if (TextUtils.isEmpty(NativePhoneNumber)) {
            return "";
        } else {
            return NativePhoneNumber;
        }
    }

    /**
     * 获取版本名字
     *
     * @param context
     * @return version name
     */
    public static int getClientVersionCode(Context context) {
        PackageManager manager = context.getPackageManager();
        try {
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            int appVersionCode = info.versionCode; // 版本名
            return appVersionCode; // 版本号
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 获取Android设备唯一编号
     *
     * @param context
     * @return deviceId
     */
    public static String getDeviceId(Context context) {
        // 设备唯一序列号(IMEI)
        TelephonyManager tm = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        String deviceId = tm.getDeviceId();
        return deviceId;
    }

    /**
     * 获取版本名字
     *
     * @param context
     * @return version name
     */
    public static String getClientVersionName(Context context) {
        PackageManager manager = context.getPackageManager();

        try {
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            String appVersion = info.versionName; // 版本名
            return appVersion; // 版本号
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 判断网络是否连接
     *
     * @param context
     * @return
     */
    public static boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager
                    .getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }

    /**
     * 获取当前时间
     *
     * @return
     */
    public static String getNowTime() {
        SimpleDateFormat sDateFormat = new SimpleDateFormat(
                "yyyy-MM-dd hh:mm:ss");
        String now = "";
        try {
            now = URLEncoder.encode(sDateFormat.format(new Date()), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return now;
    }

    /**
     * 获取格式化时间
     *
     * @param timestamp
     * @return 格式化时间
     */
    public static String getDatebyTimestamp(String timestamp) {

        Date date = new Date(Long.valueOf(timestamp));

        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String now = "";

        try {
            now = URLEncoder.encode(sDateFormat.format(date), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return now;
    }

    /**
     * 获取当前Unix时间
     *
     * @return
     */
    public static long getUnixTime() {
        return System.currentTimeMillis() / 1000;
    }

    /**
     * 判断sdcard是否存在
     *
     * @return true存在可读写 false不存在不可读写
     */
    public static boolean sdacrdExist() {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            // Log.d(TAG, "sdcard is exist,read and write ok");
            return true;
        }
        // Log.d(TAG, "sdcard is not exist or can not read/write");
        return false;
    }

    //获取屏幕的宽度
    public static int getScreenWidth(Context context) {
        WindowManager manager = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        Display display = manager.getDefaultDisplay();
        return display.getWidth();
    }

    //获取屏幕的高度
    public static int getScreenHeight(Context context) {
        WindowManager manager = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        Display display = manager.getDefaultDisplay();
        return display.getHeight();
    }

    public static String getPath(Context context, Uri uri) {
        if ("content".equalsIgnoreCase(uri.getScheme())) {
            String[] projection = {"_data"};
            Cursor cursor = null;
            try {
                cursor = context.getContentResolver().query(uri, projection, null, null, null);
                int column_index = cursor.getColumnIndexOrThrow("_data");
                if (cursor.moveToFirst()) {
                    return cursor.getString(column_index);
                }
            } catch (Exception e) {
            }
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }
        return null;
    }

    /**
     * long转时间string
     *
     * @param millis
     * @return
     */
    public static String getDateStr(long millis) {
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(millis);
        Formatter ft = new Formatter(Locale.CHINA);
        return ft.format("%1$tm月%1$td日  %1$tR", cal).toString();
    }

    /**
     * long转时间string
     *
     * @param millis
     * @return
     */
    public static String getDateStrYYYY(long millis) {
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(millis);
        Formatter ft = new Formatter(Locale.CHINA);
        return ft.format("%1$tY年%1$tm月%1$td日", cal).toString();
    }

    /**
     * long转时间string
     *
     * @return
     */
    public static String getDateStrYYYYMMDD() {
        long millis = getDateInMillis();
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(millis);
        Formatter ft = new Formatter(Locale.CHINA);
        return ft.format("%1$tY-%1$tm-%1$td", cal).toString();
    }

    public static long getDateInMillis() {
        return Calendar.getInstance().getTimeInMillis();
    }

    /**
     * long转时间string
     *
     * @param millis
     * @return
     */
    public static String getDateStrMMDD(long millis) {
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(millis);
        Formatter ft = new Formatter(Locale.CHINA);
        return ft.format("%1$tm-%1$td", cal).toString();
    }

    public static int getDipLength(Context mContext, int size) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, size, mContext.getResources().getDisplayMetrics());
    }

    public static int getSpLength(Context mContext, int size) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, size, mContext.getResources().getDisplayMetrics());
    }

    /**
     * 时间String转long
     * @param time
     * @return
     */
    public static String getTime(String time) {
        if (TextUtils.isEmpty(time)) {
            return "";
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date date = sdf.parse(time);
            Calendar c = Calendar.getInstance();
            c.setTime(date);
            Formatter ft = new Formatter(Locale.CHINA);
            return ft.format("%1$tm/%1$td", c).toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String getTime(Calendar c) {
        Formatter ft = new Formatter(Locale.CHINA);
        return ft.format("%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS", c).toString();
    }

    public static String getTime(Date date) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        Formatter ft = new Formatter(Locale.CHINA);
        return ft.format("%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS", c).toString();
    }

    public static String getTimeYEAR_MONTH_DAY(Date date) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        Formatter ft = new Formatter(Locale.CHINA);
        return ft.format("%1$tY-%1$tm-%1$td", c).toString();
    }

    public static String getTimeHOURS_MINS(Date date) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        Formatter ft = new Formatter(Locale.CHINA);
        return ft.format("%1$tH:%1$tM:%1$tS", c).toString();
    }

    /**
     * 时间String转年月日
     * @param time
     * @return
     */
    public static String getYYYYMMDD(String time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date date = sdf.parse(time);
            Calendar c = Calendar.getInstance();
            c.setTime(date);
            Formatter ft = new Formatter(Locale.CHINA);
            return ft.format("%1$tY-%1$tm-%1$td", c).toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 时间String转年月日
     * @param time
     * @return
     */
    public static String getMMSS(String time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date date = sdf.parse(time);
            Calendar c = Calendar.getInstance();
            c.setTime(date);
            Formatter ft = new Formatter(Locale.CHINA);
            return ft.format("%1$tR", c).toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}
